package mushystuff.dtb.web.components;

import java.util.SortedSet;

import mushystuff.dtb.core.model.Product;
import mushystuff.dtb.core.model.UserStory;
import mushystuff.dtb.core.service.ProductService;

import org.apache.tapestry5.RenderSupport;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.annotations.IncludeJavaScriptLibrary;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.ioc.annotations.Inject;

@SuppressWarnings("unused")
@IncludeJavaScriptLibrary({"${tapestry.scriptaculous}/dragdrop.js"})
public class ProductBacklogList {
    
    @Parameter(allowNull=false, required=true)
    @Property
    private Product product;
    
    @Property
    private UserStory userStory;
    
    @Property
    private UserStory newUserStory;
    
    @Inject
    private ProductService productService;
    
    @Environmental
    private RenderSupport renderSupport;
    
    @SetupRender
    void init() {
        newUserStory = new UserStory();
        renderSupport.addScript("$('productBacklog_" + product.getId() + "').select('li').each( function(li) {new Draggable(li, { revert: true, handle: 'handle' });});");
        renderSupport.addScript("Droppables.add('productBacklog_" + product.getId() + "', {onDrop: function(draggable, droppable, event) { droppable.appendChild(draggable); }});");
    }
    
    @OnEvent(component="newUserStory", value="success")
    void saveUserStory() {
        productService.addUserStoryToBacklog(product, newUserStory);
        newUserStory = new UserStory();
    }
    
    @OnEvent(component="removeUserStory", value="action")
    void removeUserStory(long userStoryId) {
        productService.removeUserStoryFromBacklog(userStoryId);
    }

}
